<template>
  <div class="flow-query">
    <a-card>
      <template #title>
        <div class="card-title">手动执行</div>
      </template>
      <div class="app-container">
        <!-- 右上角提示和手动执行按钮 -->
        <div class="top-right">
          <div class="instructions">
            <!-- 绿色代表可选点位，黄色代表执行任务中，蓝色代表开始点位，紫色代表目的点位 -->
             <span class="green-text"></span>代表可选点位，
             <span class="yellow-text"></span>代表执行任务中，
             <span class="blue-text"></span>代表开始点位，
             <span class="violet-text"></span>代表目的点位
          </div>
          <a-button type="primary" @click="executeManualOperation"
            >手动执行</a-button
          >
        </div>

        <!-- 库位分布图 -->
        <div class="warehouse-layout">
          <div class="title-row">
            <div class="material-group-title">母车库位B区</div>
            <div class="material-group-title">母车库位A区</div>
          </div>

          <!-- 第一行：两组母车 -->
          <div class="row material-row">
            <!-- 母车A -->
            <div class="material-group" v-if="materialB.length > 0">
              <div
                v-for="n in materialB"
                :key="n.id"
                class="slot material"
                :class="[slots.materialB[n.columnLoc - 1]?.status]"
                @click="selectSlot('materialB', 1, n.columnLoc)"
                style="white-space: pre-line; text-align: center"
              >
                {{ slots.materialB[n.columnLoc - 1]?.label }}
              </div>
            </div>
            <div v-else class="no-location"> 该区域无库位 </div>

            <!-- 母车B -->
            <div class="material-group" v-if="materialB.length > 0">
              <div
                v-for="n in materialA"
                :key="n.id"
                class="slot material"
                :class="[slots.materialA[n.columnLoc - 1]?.status]"
                @click="selectSlot('materialA', 1, n.columnLoc)"
                style="white-space: pre-line; text-align: center"
              >
                {{ slots.materialA[n.columnLoc - 1]?.label }}
              </div>
            </div>
            <div v-else class="no-location"> 该区域无库位 </div>
          </div>

          <!-- 第二行：空行 -->
          <div class="title-row2">
            <div class="material-group-title">卸车缓存区</div>
            <div class="material-group-title">装车缓存区</div>
            <div class="material-group-title">料车待配送区</div>
          </div>

          <!-- 第三行：分左右两部分 -->
          <div class="main-row">
            <!-- 左边部分 -->
            <div class="left-section">
              <!-- 第一行：4个卸货位 -->
              <div class="unload-row" v-if="unload.length > 0">
                <div
                  v-for="n in unload"
                  :key="n.id"
                  class="slot unload"
                  :class="[slots.unload[n.columnLoc - 1]?.status]"
                  @click="selectSlot('unload', 1, n.columnLoc)"
                  style="white-space: pre-line; text-align: center"
                >
                  {{ slots.unload[n.columnLoc - 1]?.label }}
                </div>
              </div>
              <div v-else class="no-location"> 该区域无库位 </div>

              <!-- 第二行：两个提升机位 -->
              <div class="lift-row">
                <div v-if="liftUnload.length > 0" class="lift-group">
                  <div
                    v-for="n in liftUnload"
                    :key="n.id"
                    class="slot lift"
                    :class="[slots.liftUnload[n.columnLoc - 1]?.status]"
                    @click="selectSlot('liftUnload', 1, n.columnLoc)"
                    style="white-space: pre-line; text-align: center"
                    >{{ slots.liftUnload[n.columnLoc - 1]?.label }}</div
                  >
                </div>
                <div v-else class="no-location">该区域无库位</div>
                <div v-if="liftLoad.length > 0" class="lift-group">
                  <div
                    v-for="n in liftLoad"
                    :key="n.id"
                    class="slot lift"
                    :class="[slots.liftLoad[n.columnLoc - 1]?.status]"
                    @click="selectSlot('liftLoad', 1, n.columnLoc)"
                    style="white-space: pre-line; text-align: center"
                    >{{ slots.liftLoad[n.columnLoc - 1]?.label }}</div
                  >
                </div>
                <div v-else class="no-location">该区域无库位</div>
              </div>
            </div>

            <!-- 右边部分 - 两个大块 -->
            <div class="right-section">
              <!-- 第一个大块：6排5列的点位 -->
              <div class="large-block" v-if="loadingCache.length > 0">
                <div
                  v-for="(row, rowIndex) in loadingCacheGrid"
                  :key="'loadingCacheRow-' + rowIndex"
                  class="small-block"
                >
                  <div
                    v-for="(col, colIndex) in row"
                    :key="'loadingCacheCol-' + colIndex"
                    class="slot agv"
                    :class="
                      col
                        ? slots.loadingCache[
                            getIndexByRowCol(
                              'loadingCache',
                              rowIndex + 1,
                              colIndex + 1
                            )
                          ]?.status
                        : 'empty'
                    "
                    @click="
                      col
                        ? selectSlot('loadingCache', rowIndex + 1, colIndex + 1)
                        : null
                    "
                    style="white-space: pre-line; text-align: center"
                  >
                    {{
                      col
                        ? getLabel('loadingCache', rowIndex + 1, colIndex + 1)
                        : ''
                    }}
                  </div>
                </div>
              </div>
              <div v-else class="no-location">该区域无库位</div>

              <!-- 第二个大块：6排5列的点位 -->
              <div class="large-block" v-if="delivered.length > 0">
                <div
                  v-for="(row, rowIndex) in deliveryGrid"
                  :key="'deliveryRow-' + rowIndex"
                  class="small-block"
                >
                  <div
                    v-for="(col, colIndex) in row"
                    :key="'deliveryCol-' + colIndex"
                    class="slot delivery"
                    :class="
                      col
                        ? slots.delivery[
                            getIndexByRowCol(
                              'delivery',
                              rowIndex + 1,
                              colIndex + 1
                            )
                          ].status
                        : 'empty'
                    "
                    @click="
                      col
                        ? selectSlot('delivery', rowIndex + 1, colIndex + 1)
                        : null
                    "
                    style="white-space: pre-line; text-align: center"
                  >
                    <!-- {{ getLabel('delivery', rowIndex + 1, colIndex + 1) }} -->
                    {{
                      col
                        ? getLabel('delivery', rowIndex + 1, colIndex + 1)
                        : ''
                    }}
                  </div>
                </div>
              </div>
              <div v-else class="no-location">该区域无库位</div>
            </div>
          </div>
        </div>
      </div>
    </a-card>
  </div>
</template>
  
  <script setup lang="ts">
import {
  computed,
  onActivated,
  onDeactivated,
  onMounted,
  onUnmounted,
  Ref,
  ref,
  watch,
} from 'vue';
import { Slot, Location } from '@/api/les/types';
import { queryAllCarLocation, manualDelivery } from '@/api/les/index';
import { Notification } from '@arco-design/web-vue';

const materialA = ref<any[]>([]);
const materialB = ref<any[]>([]);
const unload = ref<any[]>([]);
const liftLoad = ref<any[]>([]);
const liftUnload = ref<any[]>([]);
const loadingCache = ref<any[]>([]);
const delivered = ref<any[]>([]);
const locationInterval = ref<number | null>(null);

// 初始化所有槽位
const slots = ref<Record<string, Slot[]>>({
  materialA: Array.from({ length: materialA.value.length }, () => ({
    label: '母车',
    status: '',
  })),
  materialB: Array.from({ length: materialB.value.length }, () => ({
    label: '母车',
    status: '',
  })),
  unload: Array.from({ length: unload.value.length }, () => ({
    label: '卸车缓存',
    status: '',
  })),
  liftUnload: Array.from({ length: liftUnload.value.length }, () => ({
    label: '卸车位',
    status: '',
  })),
  liftLoad: Array.from({ length: liftLoad.value.length }, () => ({
    label: '装车位',
    status: '',
  })),
  loadingCache: Array.from({ length: loadingCache.value.length }, () => ({
    label: '装车缓存',
    status: '',
  })),
  delivery: Array.from({ length: delivered.value.length }, () => ({
    label: '待配送',
    status: '',
  })),
});

const loadingCacheGrid = computed(() => {
  const grid: Record<string, any>[][] = [];

  loadingCache.value.forEach((item) => {
    const row = parseInt(item.rowLoc, 10);
    const col = parseInt(item.columnLoc, 10);

    if (!grid[row - 1]) {
      grid[row - 1] = [];
    }

    grid[row - 1][col - 1] = item;
  });

  return grid;
});

const deliveryGrid = computed(() => {
  const grid: Record<string, any>[][] = [];

  delivered.value.forEach((item) => {
    const row = parseInt(item.rowLoc, 10);
    const col = parseInt(item.columnLoc, 10);

    if (!grid[row - 1]) {
      grid[row - 1] = [];
    }

    grid[row - 1][col - 1] = item;
  });

  return grid;
});

const isPaused = ref(false);
const selectedStart = ref<[string, number, number] | null>(null);
const selectedEnd = ref<[string, number, number] | null>(null);

function getIndexByRowCol(
  type: string,
  targetRow: number,
  targetCol: number
): number {
  let data: any[] = [];
  if (type === 'loadingCache') data = loadingCache.value;
  else if (type === 'delivery') data = delivered.value;
  else return targetCol - 1; // 非网格区域直接返回列索引

  // 查找匹配的行列数据
  const item = data.find(
    (i) =>
      parseInt(i.rowLoc, 10) === targetRow &&
      parseInt(i.columnLoc, 10) === targetCol
  );
  return item ? data.indexOf(item) : -1; // 找不到返回 -1
}

// 获取指定槽位的标签
const getLabel = (type: string, row: number, col: number): string => {
  const index = getIndexByRowCol(type, row, col);
  if (index === -1) return ''; // 未找到返回空字符串

  const slot = slots.value[type]?.[index]; // 添加可选链操作符
  return slot?.label || ''; // 如果 slot 不存在或 label 为空，则返回空字符串
};

// 选择槽位
const selectSlot = (type: string, row: number, col: number) => {
  isPaused.value = true;
  let index = 0;
  if (type === 'loadingCache' || type === 'delivery') {
    index = getIndexByRowCol(type, row, col);
  } else {
    index = col - 1;
  }

  // 安全检查
  if (!slots.value[type] || !slots.value[type][index]) {
    console.warn('无效的槽位:', type, row, col, index);
    return;
  }

  const slot = slots.value[type][index];

  // 如果再次点击已选的开始或结束位置，则恢复为正常状态
  if (
    (selectedStart.value &&
      selectedStart.value[0] === type &&
      selectedStart.value[1] === row &&
      selectedStart.value[2] === col) ||
    (selectedEnd.value &&
      selectedEnd.value[0] === type &&
      selectedEnd.value[1] === row &&
      selectedEnd.value[2] === col)
  ) {
    if (slot.status === 'start') {
      slot.status = 'normalGreen';
    }
    if (slot.status === 'end') {
      slot.status = 'normalGreen';
    }
    if (
      selectedStart.value &&
      selectedStart.value[0] === type &&
      selectedStart.value[1] === row &&
      selectedStart.value[2] === col
    ) {
      selectedStart.value = null;
    } else if (
      selectedEnd.value &&
      selectedEnd.value[0] === type &&
      selectedEnd.value[1] === row &&
      selectedEnd.value[2] === col
    ) {
      selectedEnd.value = null;
    }
    return;
  }
  if (selectedStart.value === null) {
    // 如果没有选择开始位置，则选择当前槽位作为开始位置
    if (slot.status === 'normalGreen' || slot.status === 'normalYellow') {
      slot.status = 'start';
      selectedStart.value = [type, row, col];
    }
  } else if (selectedEnd.value === null) {
    // 如果已经选择了开始位置但没有选择结束位置，则选择当前槽位作为结束位置
    if (slot.status === 'normalGreen' || slot.status === 'normalYellow') {
      slot.status = 'end';
      selectedEnd.value = [type, row, col];
    }
  }
  // 如果已经选择了开始位置和结束位置，则不进行任何操作
};

// 重置选择
const resetSelections = () => {
  Object.keys(slots.value).forEach((type) => {
    slots.value[type].forEach((slot) => {
      if (slot.status === 'start') {
        slot.status = 'normalGreen';
      }
      if (slot.status === 'end') {
        slot.status = 'normalGreen';
      }
    });
  });
  selectedStart.value = null;
  selectedEnd.value = null;
};

// 执行手动操作
async function executeManualOperation() {
  if (selectedStart.value !== null && selectedEnd.value !== null) {
    const startPort = ref('');
    const endPort = ref('');
    const locationMap: Record<string, Ref<Location[]>> = {
      materialA,
      materialB,
      unload,
      liftLoad,
      liftUnload,
      loadingCache,
      delivered,
    };
    const [typeStart, rowStart, colStart] = selectedStart.value;
    const [typeEnd, rowEnd, colEnd] = selectedEnd.value;
    const locationsStart = locationMap[typeStart];
    const locationsEnd = locationMap[typeEnd];
    if (locationsStart) {
      const startLocation = locationsStart.value.find(
        (loc: any) =>
          loc.rowLoc === rowStart.toString() &&
          loc.columnLoc === colStart.toString()
      );
      startPort.value = startLocation?.port || '';
    }
    if (locationsEnd) {
      const startLocation = locationsEnd.value.find(
        (loc: any) =>
          loc.rowLoc === rowEnd.toString() &&
          loc.columnLoc === colEnd.toString()
      );
      endPort.value = startLocation?.port || '';
    }
    if (startPort.value !== '' && endPort.value !== '') {
      await manualDelivery({
        carStartPosition: startPort.value,
        carEndPosition: endPort.value,
      }).then((res) => {
        if (res.retCode === "200") {
          Notification.success({
            title: '成功',
            content: res.message,
            closable: true,
          });
        } else {
          Notification.error({
            title: '错误',
            content: res.message,
            closable: true,
          });
        }
      });
    } else {
      Notification.error({
        title: '错误',
        content: '点位信息有误',
        closable: true,
      });
    }
    resetSelections();
  } else {
    Notification.warning({
      title: '提示',
      content: '请选择点位',
      closable: true,
    });
  }
}

function getLabelByType(item: any): string {
  switch (item.type) {
    case 2:
      return item.occupiedCode ? '母车\n(有料车)' : '母车';
    case 11:
      return item.occupiedCode ? '卸车缓存\n(有料车)' : '卸车缓存';
    case 8:
      return item.occupiedCode ? '装车位\n(有料车)' : '装车位';
    case 9:
      return item.occupiedCode ? '卸车位\n(有料车)' : '卸车位';
    case 10:
      return item.occupiedCode ? '装车缓存\n(有料车)' : '装车缓存';
    case 3:
      return item.occupiedCode ? '待配送\n(有料车)' : '待配送';
    default:
      return '未知';
  }
}

function setColor(item: any) {
  if (item.isTask === 0) {
    return 'normalGreen';
  }
  if (item.isTask === 1) {
    return 'normalYellow';
  }
  // if (item.occupiedCode && item.isTask === 1) {
  //   return 'normalRed';
  // }
  return '';
}

function setSlotStatus(data: any[]): Slot[] {
  return data.map((item) => ({
    label: getLabelByType(item),
    status: setColor(item),
  }));
}

// 设置库位信息并设置槽位状态
async function setLocation() {
  // 先排序
  materialA.value.sort(
    (a, b) => parseInt(a.columnLoc, 10) - parseInt(b.columnLoc, 10)
  );
  materialB.value.sort(
    (a, b) => parseInt(a.columnLoc, 10) - parseInt(b.columnLoc, 10)
  );
  unload.value.sort(
    (a, b) => parseInt(a.columnLoc, 10) - parseInt(b.columnLoc, 10)
  );
  liftLoad.value.sort(
    (a, b) => parseInt(a.columnLoc, 10) - parseInt(b.columnLoc, 10)
  );
  liftUnload.value.sort(
    (a, b) => parseInt(a.columnLoc, 10) - parseInt(b.columnLoc, 10)
  );
  loadingCache.value.sort(
    (a, b) => parseInt(a.columnLoc, 10) - parseInt(b.columnLoc, 10)
  );
  delivered.value.sort(
    (a, b) => parseInt(a.columnLoc, 10) - parseInt(b.columnLoc, 10)
  );
  // 更新 slots 状态
  slots.value.materialA = setSlotStatus(materialA.value);
  slots.value.materialB = setSlotStatus(materialB.value);
  slots.value.unload = setSlotStatus(unload.value);
  slots.value.liftLoad = setSlotStatus(liftLoad.value);
  slots.value.liftUnload = setSlotStatus(liftUnload.value);
  slots.value.loadingCache = setSlotStatus(loadingCache.value);
  slots.value.delivery = setSlotStatus(delivered.value);
}

// 获取库位信息
async function getLocation() {
  await queryAllCarLocation().then((res) => {
    if (res.retCode !== '200') {
      Notification.error({
        title: '错误',
        content: '未获取到库位信息',
        closable: true,
      });
      return;
    }
    materialA.value = [];
    materialB.value = [];
    unload.value = [];
    liftLoad.value = [];
    liftUnload.value = [];
    loadingCache.value = [];
    delivered.value = [];
    const allLocation = res.responseBody;
    if (allLocation) {
      allLocation.forEach((location: any) => {
        if (
          location.type === 2 &&
          location.area === '101' &&
          location.part === 'A' &&
          location.rowLoc === '1' &&
          location.tierLoc === '1'
        ) {
          materialA.value.push(location);
        }
        if (
          location.type === 2 &&
          location.area === '101' &&
          location.part === 'B' &&
          location.rowLoc === '1' &&
          location.tierLoc === '1'
        ) {
          materialB.value.push(location);
        }
        if (location.type === 11 && location.area === '101') {
          unload.value.push(location);
        }
        if (location.type === 8 && location.area === '101') {
          liftLoad.value.push(location);
        }
        if (location.type === 9 && location.area === '101') {
          liftUnload.value.push(location);
        }
        if (location.type === 10 && location.area === '101') {
          loadingCache.value.push(location);
        }
        if (location.type === 3 && location.area === '101') {
          delivered.value.push(location);
        }
      });
    }
  });
  await setLocation();
}

function startPolling() {
  if (locationInterval.value === null) {
    locationInterval.value = window.setInterval(() => {
      if (!isPaused.value) {
        getLocation();
      }
    }, 1000);
  }
}

function clearTimer() {
  if (locationInterval.value !== null) {
    window.clearInterval(locationInterval.value);
    locationInterval.value = null;
  }
}

// 首次加载或重新激活时都执行
function initLocationAndStartPolling() {
  getLocation(); // 立即获取一次数据
  startPolling();        // 启动轮询
}

// onMounted(() => {
//   initLocationAndStartPolling();
// });

onActivated(() => {
  initLocationAndStartPolling();
});

onDeactivated(() => {
  clearTimer();
});

// onUnmounted(() => {
//   clearTimer();
// });

// 监听 selectedStart 和 selectedEnd 的变化，控制轮询的暂停与恢复
watch([selectedStart, selectedEnd], ([newStart, newEnd]) => {
  isPaused.value = !!newStart || !!newEnd;
});
</script>
  
  <style scoped>
.flow-query {
  padding: 20px;
  height: 80vh;
}

.app-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background-color: #efeeee;
  color: #333;
  width: 100%;
  height: 70vh;
}

.top-right {
  display: flex;
  justify-content: flex-end;
  width: 100%;
  margin-bottom: 20px;
}

.instructions {
  margin-right: 20px;
  margin-top: 8px;
}

.blue-text {
  background-color: #a3e7fd;
}
.green-text {
  background-color: rgb(160, 253, 136);
}
.red-text {
  color: rgb(252, 36, 36);
}
.yellow-text {
  background-color: rgb(254, 246, 128);
}
.violet-text {
  background-color: #ee06fa;
}

.green-text,
.yellow-text,
.blue-text,
.violet-text {
  width: 16px;
  height: 16px;
  gap: 8px;
  display: inline-block;
  vertical-align: middle;
}

.warehouse-layout {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: auto;
  border: 1px solid #555;
  padding: 10px;
}

.no-location {
  font-size: 1vw;
  color: #f80000;
  text-align: center;
  width: 100%;
}

/* 第一行 - 母车行 */
.title-row {
  width: 100%;
  display: flex;
  justify-content: space-between; /* 左右对齐 */
  margin: 20px 0px 20px 0px;
  padding: 0 5vw; /* 距离左右两端各 50px */
}
.title-row2 {
  width: 100%;
  display: flex;
  justify-content: space-between; /* 左右对齐 */
  margin: 20px 0px 20px 0px;
  padding: 0 10vw; /* 距离左右两端各 50px */
}

.material-group-title {
  font-size: 1vw;
  /* font-weight: bold; */
  color: #000000;
}

.material-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.material-group {
  display: flex;
  gap: 10px;
}

/* 第二行 - 空行 */
.empty-row {
  height: 20px;
  margin-bottom: 10px;
}

/* 第三行 - 主内容行 */
.main-row {
  display: flex;
  width: 100%;
  gap: 6vw; /* 左右两部分中间的间隙 */
}

/* 左边部分 */
.left-section {
  display: flex;
  flex-direction: column;
  width: 30%;
}

.unload-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.lift-row {
  display: flex;
  justify-content: space-between;
}

/* 右边部分 */
.right-section {
  display: flex;
  gap: 10px;
  width: 70%;
}

.large-block {
  display: flex;
  flex-direction: column;
  gap: 5px;
  width: 50%;
}

.small-block {
  display: flex;
  flex-wrap: nowrap;
  gap: 5px;
}

.slot {
  width: 4vw;
  height: 5.5vh;
  display: flex;
  padding: 2px;
  font-size: 0.8vw;
  justify-content: center;
  align-items: center;
  border: 1px solid #efeeee;
  cursor: pointer;
  background-color: #efeeee; /* 默认绿色 */
}

.slot.normalYellow {
  background-color: rgb(254, 246, 128);
}

.slot.normalGreen {
  background-color: rgb(160, 253, 136); /* 绿色 */
}

.slot.normalRed {
  background-color: rgb(252, 36, 36); /* 红色 */
}

.slot.start {
  background-color: #a3e7fd;
}

.slot.end {
  background-color: #ee06fa; /* 紫色 */
}

/* 滚动条样式 */
.warehouse-layout::-webkit-scrollbar {
  width: 8px;
}

.warehouse-layout::-webkit-scrollbar-track {
  background: #efeeee;
}

.warehouse-layout::-webkit-scrollbar-thumb {
  background: #b3b3b3;
  border-radius: 4px;
}
</style>